package JavaThread.TwoPhaseTermination;


import lombok.extern.slf4j.Slf4j;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c. TPT")
public class TPT {
    private Thread monitor;

    public static void main(String[] args) throws InterruptedException {
        TPT tpt1 = new TPT();

            tpt1.start();
            Thread.sleep(2000);
            tpt1.stop();


    }

    public void start(){
        monitor = new Thread(() -> {
            while (true){
                Thread thread = Thread.currentThread();
                if (thread.isInterrupted()){
                    log.debug("料理后事");
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                    log.debug("监控线程");
                } catch (InterruptedException e) {
                    //如果是睡眠异常会清除标记为false，使用interrupt再次打断标记，设置为true
                    thread.interrupt();
                    //如果是正常，那么打断标记本身就为true，不会进入异常
                    e.printStackTrace();

                }
            }
        });

        monitor.start();
    }

    public void stop(){
        monitor.interrupt();

    }
}
